這個是我之前沒有接觸到的功能, 最近這幾天大概跟新手一樣都在摸索 TreeWidget, 那麼就跟我一起從官網的Displaying Data Using a Tree Widget開始吧
以下是把官方的展示程式碼兜起來後的樣子
import sys
from PySide6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
data = {"Project A": ["file_a.py", "file_a.txt", "something.xls"],
"Project B": ["file_b.csv", "photo.jpg"],
"Project C": []}
app = QApplication()
tree = QTreeWidget()
tree.setColumnCount(2)
tree.setHeaderLabels(["Name", "Type"])
items = []
for key, values in data.items():
item = QTreeWidgetItem([key])
for value in values:
ext = value.split(".")[-1].upper()
child = QTreeWidgetItem([value, ext])
item.addChild(child)
items.append(item)
tree.insertTopLevelItems(0, items)
tree.show()
sys.exit(app.exec())
執行後的畫面如圖所示
讓我想想這個 QTreeWidget 可不可以跟前面用過的元件結合, QLabel 應該是萬能的吧, 試試看能不能把前幾天的表格內容物用 QTreeWidget 呈現
不過要先想一下用表格呈現的 list 遊戲角色資料要怎樣的方式換成 dictionary 方式存
總之先試試看
import sys
from PySide6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
data = {"Saber": [],
"Archer": ["EMIYA", "Gilgamesh", "Arjuna", "Kid Gilgamesh"],
"Lancer": ["Cu Chulainn", "Karna"],
"Rider": ["Alexander"],
"Caster": ["Zhuge Liang (El-Melloi II)", "Solomon (Grand Caster)"],
"Assassin": [],
"Berserker": ["Cu Chulainn (Alter)"],
"Avenger" : ["Edmond Dantes"]}
app = QApplication()
tree = QTreeWidget()
tree.setColumnCount(2)
tree.setHeaderLabels(["Class", "Name"])
items = []
for key, values in data.items():
item = QTreeWidgetItem([key])
for value in values:
ext = value.split(".")[-1].upper()
child = QTreeWidgetItem([value, ext])
item.addChild(child)
items.append(item)
tree.insertTopLevelItems(0, items)
tree.show()
sys.exit(app.exec())
嘗試結果
哭啊, 弄錯方向了
雖然用職階去分類這是對的, 但是標題欄位錯了, 要重新調整一下然後加資料
由於之前都是接觸比較多 C++, 所以多花了一些時間摸索 Python 的 dictionary
import sys
from PySide6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
data = {"Saber": {},
"Archer": {"EMIYA": {"star": "4"}, "Gilgamesh": {"star": "5"}, "Arjuna": {"star": "5"}, "Kid Gilgamesh": {"star": "3"}},
"Lancer": {"Cu Chulainn": {"star": "3"}, "Karna": {"star": "5"}},
"Rider": {"Alexander": {"star": "3"}},
"Caster": {"Zhuge Liang (El-Melloi II)": {"star": "5"}, "Solomon (Grand Caster)": {"star": "5"}},
"Assassin": {},
"Berserker": {"Cu Chulainn (Alter)": {"star": "5"}},
"Avenger" : {"Edmond Dantes": {"star": "5"}}}
app = QApplication()
tree = QTreeWidget()
tree.setColumnCount(2)
tree.setHeaderLabels(["Servant", "Star"])
items = []
for key, values in data.items():
item = QTreeWidgetItem([key])
for name, star in values.items():
child = QTreeWidgetItem([name, star["star"]])
item.addChild(child)
items.append(item)
tree.insertTopLevelItems(0, items)
tree.show()
sys.exit(app.exec())
展示如下
總算是有個樣子了, 總覺得今天主要是在複習如何存取 dictionary 的資料型態, 那個 items() 是 dictionary 的關鍵字啊
今天就只有用到一點感覺很可惜, 都沒有把前幾天用的元件塞進去, 明天來試試把圖案, 尤其是星號放入 Header 裡, 接下來再試試把按鈕放到第三格, 另外 QTreeWidget 中有 addChild() 這個功能, 也想嘗試能不能在 child 裡再使用 addChild()